import { queryArticleList } from "@/api/article.api";
import { ArticleList } from "@/types/article";
import { Pagination } from "@/types/pagination";
import { Ref, onMounted, reactive, ref, toRaw } from "vue";

export const useArticleList = (): {
  articleList: Ref<ArticleList>;
  pagination: Pagination;
  tagChange: (id: string) => void;
  categoryChange: (id: string) => void;
  goToPage: () => void;
} => {
  const tagId = ref("");
  const category = ref("");
  const articleList = ref<ArticleList>([]);
  const pagination = reactive<Pagination>({
    pageNo: 1,
    pageSize: 30,
    total: 0,
  });
  const getArticleList = async () => {
    const { pageNo, pageSize } = toRaw(pagination);
    const params = {
      pageNo,
      pageSize,
      categoryId: category.value || "",
      tagIds: tagId.value ? [tagId.value] : [],
    };
    const res = await queryArticleList(params);
    if (res.code === 200 && res.data) {
      const list = res.data.rows || [];
      articleList.value = pageNo === 1 ? list : articleList.value.concat(list);
      pagination.total = res.data.total || 0;
    }
  };
  const tagChange = (id: string): void => {
    tagId.value = id;
    pagination.pageNo = 1;
    getArticleList();
  };
  const categoryChange = (id: string): void => {
    category.value = id;
    pagination.pageNo = 1;
    getArticleList();
  };
  const goToPage = (): void => {
    pagination.pageNo++;
    getArticleList();
  };
  onMounted(() => {
    getArticleList();
  });
  return {
    articleList,
    pagination,
    tagChange,
    categoryChange,
    goToPage,
  };
};
